import os
import re
from pathlib import Path
from natsort import natsorted

# valid_exts = {'.dwg', '.dxf', '.pdf'}


# def is_ext_valid(file):
#     _, ext = os.path.splitext(file)
#     return ext in valid_exts


reg_lwh = re.compile(r'(\d{3,4})\s*x(\d{3,4})\s*x(\d{3,4})', re.IGNORECASE)


def search_lwh(fn, k):
    ms = reg_lwh.search(fn)
    if not ms:
        return False
    l, w, h = ms.group(1), ms.group(2), ms.group(3)
    realk = k.replace('l', l).replace('w', w).replace('h', h)
    return eval(realk)


def search_folder(folder, includes_str, range, chk1, chk2, chk3, chk4):
    founds = []
    print(f'搜索开始{folder} 关键字{includes_str} 范围{range}')
    for (dirpath, dirnames, filenames) in os.walk(folder):
        # print(filenames)
        d_path = Path(dirpath)
        d_name = d_path.name
        includes = set(p.strip() for p in includes_str.split())
        # if includes and not all(i in d_name for i in includes):
        #     continue
        if range and chk4 and not search_lwh(d_name, range):
            continue
        matching_files = []
        if chk4 and all(i in d_name for i in includes):
            matching_files.append(d_path)
        for f in filenames:
            if f.endswith('.dxf'):
                if not chk1:
                    continue
            elif f.endswith('.dwg'):
                if not chk2:
                    continue
            elif f.endswith('.pdf'):
                if not chk3:
                    continue
            else:
                continue
            full = d_path / f
            if (all(i in f for i in includes)) and (search_lwh(f, range)):
                matching_files.append(full)
        for item in natsorted(matching_files):
            founds.append(item.as_posix())
            # print(item)
    print(f'搜索结束{folder} 关键字{includes_str} 范围{range}\n')
    return founds
